package cn.fzm.ssm.controller;

import cn.fzm.ssm.domain.Role;
import cn.fzm.ssm.domain.UserInfo;
import cn.fzm.ssm.service.IRoleService;
import cn.fzm.ssm.service.IUserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author Dremeue
 * @create 2019-10-12 14:33
 **/
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @RequestMapping("/findById.do")
    public ModelAndView findById(String id) {
        ModelAndView mv = new ModelAndView();
        UserInfo userInfo = userService.findById(id);
        mv.addObject("user", userInfo);
        mv.setViewName("user-show");
        return mv;
    }

    @RequestMapping("/findAll.do")
    public ModelAndView findAll(@RequestParam(required = true, name = "page") int pageNum, @RequestParam(required =
            true, name = "pageSize") int pageSize) {
        ModelAndView mv = new ModelAndView();
        List<UserInfo> userList = userService.findAll(pageNum, pageSize);
        PageInfo pageInfo = new PageInfo(userList);
        mv.addObject("pageInfo", pageInfo);
        mv.setViewName("user-list");

        return mv;
    }

    @RequestMapping("/save.do")
    public String save(UserInfo userInfo) {
        userService.save(userInfo);
        return "redirect:findAll.do?page=1&pageSize=4";
    }

    @RequestMapping("/deleteByIds.do")
    public String deleteByIds(String ids) {
        System.out.println(ids);
        String[] userIds = ids.split(",");
       userService.deleteByIds(userIds);
        return "redirect:findAll.do?page=1&pageSize=4";
    }

    /**
     * 查找要操作的用户和该用户可添加的角色
     * @param id
     * @return
     */
    @RequestMapping("/findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(String id) {
        ModelAndView mv = new ModelAndView();
        UserInfo userInfo = userService.findById(id);
        List<Role> roleList = roleService.findOtherRole(id);
        mv.addObject("user", userInfo);
        mv.addObject("roleList", roleList);
        mv.setViewName("user-role-add");
        return mv;
    }

    @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(String userId, String[] ids) {
        userService.addRoleToUser(userId, ids);
        return "redirect:findAll.do?page=1&pageSize=4";
    }
}
